package com.aisafer.fms.action;

import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.aisafer.fms.action.CaptchaCodeUtils.CaptchaCode;

@RestController
@RequestMapping("/code")
public class RandomPictureAction {
	private static final long serialVersionUID = 7848092970366563600L;
	private ByteArrayInputStream inputStream;
	
	@RequestMapping(value = "/getCode/v1/", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void put(HttpServletRequest req, HttpServletResponse resp) {
		// 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
	
	@RequestMapping(value = "/getCode/v2/", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void getcode2(HttpServletRequest req, HttpServletResponse resp) {
		// 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
        	CaptchaCode code = CaptchaCodeUtils.getInstance().getCode();
        	
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage)code.getBufferedImage() , "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
			e.printStackTrace();
		}

    }

}
